<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二进制转字符串</title>
</head>

<body>
    <script>
        var printBin = function (num) {
            if (num < 0 || num >= 1) return 'ERROR';
            let stack = [];
            let length = 30;
            while (length > 0) {
                if (num <= 0) break;
                num *= 2;
                if (num >= 1) {
                    num--;
                    stack.push(1);
                } else {
                    stack.push(0);
                }
                length--;
            }

            /* 打印 */
            if (num === 0) {
                let res = "0."
                while (stack.length > 0) {
                    res += stack.shift()
                }
                return res
            } else {
                return "ERROR"
            }
        };

        let a = printBin(0.8);
        console.log(a);
    </script>
</body>

</html>